"""
电磁铁驱动文件
"""

from machine import Pin, PWM
from time import sleep
from .x595 import X595Driver
try:
    from typing import List
    from shared_types import ElectroMagneticPinAssignment, BIDIR_SLFHLD_EM_STATES
except:
    pass


class ElectroMagneticDriver:
    """
    电磁铁驱动类

    :pin_assignments: 引脚分配
    :x595_num: X595芯片数量，可驱动的电磁铁数量为``x595_num * 8``

    """

    def __init__(self,
                 pin_assignments: "ElectroMagneticPinAssignment",
                 x595_num: int = 1
                 ) -> None:
        self.pin_sw1 = Pin(pin_assignments["sw1"], Pin.OUT)
        self.pin_sw2 = Pin(pin_assignments["sw2"], Pin.OUT)

        self.x595 = X595Driver(pin_assignments["x595"], x595_num)

        self.pin_sw1.value(0)
        self.pin_sw2.value(0)

    def create_magnet_cmd_list(self, index: int) -> "List[int]":
        """
        创建一个驱动电磁铁的命令列表，

        其中，index代表要驱动的电磁铁，索引规则与Python中列表查询相同，
        支持负数索引；
        """
        lst = [0, 0, 0, 0, 0, 0, 0, 0]*self.x595.chip_num
        lst[index] = 1
        return lst

    def action(self, index: int, side: "BIDIR_SLFHLD_EM_STATES"):
        """
        驱动序号为index的电磁铁
        """
        if side == "A":
            self.pin_sw1.value(1)
            self.pin_sw2.value(0)
        else:
            self.pin_sw1.value(0)
            self.pin_sw2.value(1)
        cmd_lst = self.create_magnet_cmd_list(index)
        print("cmd", cmd_lst)
        self.x595.write_bits_from_list(cmd_lst)

        sleep(0.6)
        self.stop()

    def stop(self):
        self.pin_sw1.value(0)
        self.pin_sw2.value(0)
        self.x595.clear()
